package net.basshista.jsshtunneling.utils;

import java.security.InvalidKeyException;
import java.security.MessageDigest;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtils {

    private static final String ALGORITHM = "AES";

    private static MessageDigest MD5;

    private static Cipher CIPHER;

    static {
	try {
	    CIPHER = Cipher.getInstance(ALGORITHM);

	    MD5 = MessageDigest.getInstance("MD5");
	} catch (Exception e) {
	    CIPHER = null;
	}
    }

    public static byte[] decrypt(byte[] encryptBytes, String key) throws InvalidKeyException,
	    IllegalBlockSizeException, BadPaddingException {
	SecretKeySpec secretKey = new SecretKeySpec(MD5.digest(key.getBytes()), "AES");
	CIPHER.init(Cipher.DECRYPT_MODE, secretKey);

	return CIPHER.doFinal(encryptBytes);

    }

    public static byte[] encrypt(byte[] rawBytes, String key) throws InvalidKeyException, IllegalBlockSizeException,
	    BadPaddingException {

	SecretKeySpec secretKey = new SecretKeySpec(MD5.digest(key.getBytes()), "AES");
	CIPHER.init(Cipher.ENCRYPT_MODE, secretKey);

	return CIPHER.doFinal(rawBytes);
    }

}